package com.xxxx.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxxx.server.constant.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @Author:王亚栋
 * @Date: 2023/6/21 上午6:57
 * @Version:1.0
 *
 * RabbitMq 配置类
 */
@Configuration
@Slf4j(topic = "RabbitMqConfig")
public class RabbitMqConfig {

    @Resource
    private CachingConnectionFactory cachingConnectionFactory;
    @Resource
    private IMailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate(){

        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);

        /**
         * 消息确认回调,确认消息是否到达 Broker
         *
         * data : 消息唯一标识
         * ack: 确认结果
         * cause: 失败原因
         */
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {

            String msgId = data.getId();

            if (ack){

                log.info("{}======>消息发送成功！",msgId);

                //消息发送成功，保存数据库
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",1).eq("msgId",msgId));
            }else {

                log.error("{}======>消息发送失败！",msgId);

            }
        });

        /**
         * 消息失败回调 比如router不到queue的回调
         *
         * msg:  消息主题
         * respCode: 响应码
         * respText: 响应描述
         * exchange: 交换机
         * routingKey: 路由键
         */
        rabbitTemplate.setReturnCallback((msg,respCode,respText,exchange,routingKey)->{

            log.error("{}==========>消息发送queue时失败",msg.getBody());
        });

        return rabbitTemplate;
    }

    /**
     * 对列
     * @return
     */
    @Bean
    public Queue queue(){

        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    /**
     * 交换机
     * @return
     */
    @Bean
    public DirectExchange directExchange(){

        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    /**
     * 绑定对列和交换机
     * @return
     */
    @Bean
    public Binding binding(){

        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }


}
